package com.example.test_handler

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.Log
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat

/**
  handler:线程间通信
 一。原理：
 1.Handler：sendMessage方法将Message对象放到MessageQueue
 2.Message：
    target属性：哪个handler发送的消息*************
    next属性：下一个要执行的消息，按照when时间排序
 3.MessageQueue：单向链表
  enqueueMessage方法：将消息按照when时间排到消息队列中
 4.Looper：死循环不断从消息队列中取消息
    loop()-->死循环loopOnce()---->取出Message对象，调用target的dispatchMessage分发消息---》handler重写的handleMessage方法

 



 */
class MainActivity : AppCompatActivity() {
    private var  handler2:Handler? = null
    private val handler:Handler by lazy{
        object :Handler(Looper.getMainLooper()){ //主线程
            override fun handleMessage(msg: Message) {
                super.handleMessage(msg)
                if (msg.what == 101){
                    Toast.makeText(this@MainActivity,""+msg.obj,Toast.LENGTH_LONG).show()
                }
            }
            
        }
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        //子线程发送消息给主线程
        Thread{
            val message = Message.obtain()
            message.what = 101
            message.obj = "111"
            handler.sendMessage(message)
        }.start()
        //主线程发送发送消息给子线程

        Thread{
            //子线程创建handler
            Looper.prepare()
            handler2= object :Handler(){
                override fun handleMessage(msg: Message) {
                    super.handleMessage(msg)
                    Log.d("TAG", "主线程给子线程发送消息: ")
                }
            }
            Looper.loop()
        }.start()
        Thread.sleep(1000)
        handler2?.sendEmptyMessage(102)
        handler2?.post(object :Runnable{
            override fun run() {
                Log.d("TAG", "主线程发送的消息: "+Thread.currentThread().name)
            }

        })
    }
}